import { getSmCodeApi } from '@/service/user';
import { loginRule } from '@/utils/rules';
import { CodeSandboxOutlined, MobileOutlined } from '@ant-design/icons';
import { Button, Form, FormInstance, Input, message } from 'antd';
import { useEffect, useRef, useState } from 'react';

const SmCodeLogin = ({ form }: { form: FormInstance }) => {
  const [disabled, setDisabled] = useState(true);
  const [currentStatus, setCurrentStatus] = useState(true);
  let [currentTime, setCurrentTime] = useState(60);

  const timeRef = useRef<NodeJS.Timeout>();

  const checkedMobile = async () => {
    form
      .validateFields(['mobile'])
      .then(() => {
        setDisabled(false);
      })
      .catch(() => {
        setDisabled(true);
      });
  };

  //- 发送验证码组件内部进行发送
  const sendSmCode = async () => {
    setCurrentStatus(false);
    setDisabled(true);
    runTime();
    const mobile = form.getFieldValue('mobile');
    const res = await getSmCodeApi({ mobile });
    message.success(res.msg);
    form.setFieldValue('code', res.data);
  };

  //- 开始倒计时
  const runTime = () => {
    timeRef.current = setInterval(() => {
      if (currentTime === 0) {
        clearInterval(timeRef.current);
        setCurrentStatus(true);
        setDisabled(false);
        setCurrentTime(60);
        return;
      }
      setCurrentTime(--currentTime);
    }, 1000);
  };

  useEffect(() => {
    return () => {
      if (timeRef.current) {
        clearInterval(timeRef.current);
      }
    };
  }, []);
  return (
    <div>
      <Form.Item name="mobile" rules={loginRule.mobileRule} hasFeedback>
        <Input
          prefix={<MobileOutlined />}
          placeholder="请输入您的手机号码"
          onChange={checkedMobile}
        />
      </Form.Item>
      <Form.Item name="code" rules={loginRule.smCodeRule}>
        <Input
          prefix={<CodeSandboxOutlined />}
          placeholder="请输入验证码"
          addonAfter={
            <Button
              disabled={disabled}
              style={{ padding: '4px 10px', border: 'none', height: '30px' }}
              onClick={sendSmCode}
            >
              {currentStatus ? '发送验证码' : `${currentTime}秒后重新发送`}
            </Button>
          }
        />
      </Form.Item>
    </div>
  );
};

export default SmCodeLogin;
